package com.binvshe.binvshe.app;

import android.os.Bundle;
import android.support.annotation.Keep;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.binvshe.binvshe.R;
import com.binvshe.binvshe.account.AccountManager;
import com.binvshe.binvshe.account.ui.LoginActivity;
import com.binvshe.binvshe.activity.ActivityFragment;
import com.binvshe.binvshe.app.home.HomeFragment;
import com.binvshe.binvshe.app.home.OrgOneFragment;
import com.binvshe.binvshe.common.LoginEvent;
import com.binvshe.binvshe.message.MessageEvent;
import com.binvshe.binvshe.message.fragment.MessageListFragment;
import com.binvshe.binvshe.mine.MineFragment;
import com.binvshe.binvshe.mine.TestFragment;
import com.binvshe.binvshe.organization.OrganizationFragment;
import com.hyphenate.EMConversationListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.pachong.android.framework.commonui.RadioButtonBottomTabFragment;
import com.pachong.android.frameworkbase.customviews.BadgeRadioButton;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * 主界面的fragment
 *
 * @Author: PV
 * @E-mail: pengveivei@sina.cn
 * @CreateDate: 2016/6/24 15:47
 * @Version: 1.0.0
 */
public class MainBottomFragment extends RadioButtonBottomTabFragment {

    private final static int TAB_MSG = 3;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        setRadioButtonInterruptCheckedListener(TAB_MSG, new BadgeRadioButton.OnInterruptCheckedListener() {
            @Override
            public boolean onInterruptChecked(View view, boolean checked) {
                if (checked && AccountManager.getCurrentAccount() == null) {
                    LoginActivity.start(getActivity());
                    return true;
                }
                return false;
            }
        });

        setRadioButtonInterruptCheckedListener(3, new BadgeRadioButton.OnInterruptCheckedListener() {
            @Override
            public boolean onInterruptChecked(View view, boolean checked) {
                if (checked && AccountManager.getCurrentAccount() == null) {
                    LoginActivity.start(getActivity());
                    return true;
                }
                return false;
            }
        });

        return view;
    }

    @Override
    public void onPageSelected(int posi) {
        super.onPageSelected(posi);
        if (posi == TAB_MSG) {
            showMessageNotification(false);
        }
        /*SystemBarTintManager tintManager = ((MainActivity) getActivity()).tintManager;
        if (tintManager != null) {

            if (posi == 0) {
                tintManager.setTintColor(Color.parseColor("#3ac3ff"));
            } else if(posi == 4) {
                tintManager.setTintColor(Color.parseColor("#11ffffff"));
            } else {
                tintManager.setTintColor(Color.parseColor("#ffffff"));
            }
        }*/
    }

    MessageListFragment messageFragment;
    @Override
    public List<PageInfo> createPages() {

        Fragment main1Frag = new HomeFragment();
        Fragment main2Frag = new ActivityFragment();
//        Fragment organizationFragment = new OrganizationFragment();
        Fragment organizationFragment = new OrgOneFragment();
        messageFragment = new MessageListFragment();
        Fragment main5Frag = new MineFragment();
        Fragment main6Frag = new TestFragment();



//        Fragment main4Frag = new TemplateImageVPFragment();
        Fragment[] fragments = new Fragment[]{main1Frag, main2Frag, organizationFragment, messageFragment, main5Frag, main6Frag};
        String[] TITLES = new String[]{"首页", "活动购票", "社团", "消息", "我的"};
        final int[] ICONS = new int[]{R.drawable.bg_buttom_home, R.drawable.bg_buttom_activity, R.drawable.bg_buttom_information, R.drawable.bg_button_message, R.drawable.bg_buttom_mine, R.drawable.bg_buttom_mine, R.drawable.bg_buttom_mine};

        List<PageInfo> pageList = new ArrayList<>();
        for (int i = 0; i < TITLES.length; i++) {
            pageList.add(new PageInfo(fragments[i], TITLES[i], ICONS[i]));
        }

        return pageList;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        EMClient.getInstance().chatManager().addConversationListener(convListener);
        EMClient.getInstance().chatManager().addMessageListener(msgListener);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EMClient.getInstance().chatManager().removeConversationListener(convListener);
        EMClient.getInstance().chatManager().removeMessageListener(msgListener);
        EventBus.getDefault().unregister(this);
    }

    protected EMConversationListener convListener = new EMConversationListener() {

        @Override
        public void onCoversationUpdate() {
            onIMMessageReceived();
        }

    };



    EMMessageListener msgListener = new EMMessageListener() {
        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            Log.e("vivi", "onIMMessageReceived: ");
            MainBottomFragment.this.onIMMessageReceived();
        }
        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {

        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {
            MainBottomFragment.this.onIMMessageReceived();
        }

        @Override
        public void onMessageDelivered(List<EMMessage> messages) {
            MainBottomFragment.this.onIMMessageReceived();
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
            MainBottomFragment.this.onIMMessageReceived();
        }
    };


    /**
     * 接收到IM消息
     */
    private void onIMMessageReceived() {
        messageFragment.refresh();
        if (getCurrentPage() != TAB_MSG) { //不在消息页面
            showMessageNotification(true);
        }
    }

    /**
     * 接收到普通的消息
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    @Keep
    public void onCommonMessageReceived(MessageEvent msgEvent) {
        if (msgEvent != null) {
            if (getCurrentPage() != TAB_MSG) {
                showMessageNotification(true);
            }
            messageFragment.showMessageRing(true);
        }
    }
    /**
     * 接收到Login的消息
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    @Keep
    public void onLoginMessageReceived(LoginEvent loginEvent) {
        if (loginEvent != null) {
            switch (loginEvent.getAction()) {
                case LoginEvent.ACTION_LOGIN:
                    break;

                case LoginEvent.ACTION_LOGOUT:
                    setCurrentPage(0);
                    break;
            }
        }
    }

    /**
     * 显示消息的提示
     *
     * @param show
     */
    public void showMessageNotification(final boolean show) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                BadgeRadioButton rbtn = (BadgeRadioButton) mRgBottomMenu.getChildAt(TAB_MSG);
                if (show) {
                    rbtn.showPoint();
                } else {
                    rbtn.hidePoint();
                }
            }
        });

    }


}
